#define _CRT_SECURE_NO_WARNINGS 1
#include "SLT.h"
SListNode* BuySListNode(SLTDataType x) {
	SL* newnode = (SL*)malloc(sizeof(SL));
	if (newnode == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	newnode->date = x;
	newnode->next = NULL;
	return newnode;
}
void SListPrint(SListNode* plist) {
	assert(plist);
	SL* cur = plist;
	while (cur != NULL)
	{
		printf("%d ", cur->date);
		cur = cur->next;
	}
}
void SListPushBack(SListNode** pplist, SLTDataType x) {
	assert(pplist);
	SL* newnode = BuySListNode(x);
	if (*pplist == NULL)
	{
		*pplist = newnode;
	}
	else
	{
		SL* tail = *pplist;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}
void SListPushFront(SListNode** pplist, SLTDataType x) {
	assert(*pplist);
	SL* newnode = BuySListNode(x);
	newnode->next = *pplist;
	*pplist = newnode;
}
void SListPopBack(SListNode** pplist) {
	assert(pplist);
	if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{
		SL* prev = NULL;
		SL* tail = *pplist;
		while (tail->next != NULL)
		{
			prev = tail;
			tail = tail->next;
		}
		free(tail);
		prev->next = NULL;
	}
}
void SListPopFront(SListNode** pplist) {
	assert(pplist);
	SL* tail = *pplist;
	*pplist = tail->next;
	free(tail);
}
SListNode* SListFind(SListNode* plist, SLTDataType x) {
	assert(plist);
	SL* tail = plist;
	while (tail != NULL)
	{
		if (tail->date == x)
			return tail;
		tail = tail->next;
	}
	return NULL;
}
void SListInsertAfter(SL** pplist, SListNode* pos, SLTDataType x) {
	assert(pos);
	SL* tail = *pplist;
	SL* newnode = BuySListNode(x);
	while (tail != pos)
	{
		tail = tail->next;
	}
	newnode->next = tail->next;
	tail->next = newnode;
}
void SListEraseAfter(SL** pplist, SListNode* pos) {
	assert(*pplist);
	assert(pos);
	SL* tail = *pplist;
	while (tail != pos)
	{
		tail = tail->next;
	}
	pos = pos->next;
	if (pos == NULL)
		exit(-1);
	tail->next = pos->next;
	free(pos);
}
void SLTInsert(SL** pplist, SL* pos, SLTDataType x) {
	assert(pplist);
	assert(pos);
	assert(*pplist);
	SL* newnode = BuySListNode(x);
	SL* tail = *pplist;
	if (pos == tail)
	{
		*pplist = newnode;
		newnode->next = pos;
	}
	else {
		while (tail->next != pos)
		{
			tail = tail->next;
		}
		tail->next = newnode;
		newnode->next = pos;
	}
}
void SLTErase(SL** pplist, SL* pos) {
	assert(pplist);
	assert(pos);
	assert(*pplist);
	SL* tail = *pplist;
	if (pos == tail)
	{
		*pplist = pos->next;
		free(pos);
	}
	else {
		while (tail->next != pos)
		{
			tail = tail->next;
		}
		tail->next = pos->next;
		free(pos);
	}
}
void SLTDestroy(SL** pplist) {
	assert(*pplist);
	SL* tail = NULL;
	while (*pplist != NULL)
	{
		tail = *pplist;
		*pplist = (*pplist)->next;
		free(tail);
		tail = NULL;
	}
	*pplist = NULL;
}